<script setup>
import { ref, onMounted,watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import {getGridWorker,getGridWorkerByCity,getProv,getCityByProv,assignTask} from '@/api/GridWorkerAssignment';
import { ElMessage } from 'element-plus';
const route = useRoute();
const router = useRouter();


//省份列表
const provinceList = ref([])

// 城市列表
const cityList = ref([])

// 反馈者的省份和城市（用于非异地指派）
const feedbackProvince = ref('');
const feedbackCity = ref('');

// 指派表单数据
const assignmentForm = ref({
  isRemoteAssignment: false,
  province: '',
  city: '',
  remoteAssignee: ''
});

// 更新网格员列表
const gridWorkerList = ref([]);
// 存储反馈信息ID
const feedbackId = ref('');
// 定义详情数据
const detailData = ref([
  { label: '公众监督反馈信息编号', value: '' },
  { label: '反馈者信息', value: [] },
  { label: '反馈者联系电话', value: '' },
  { label: '反馈信息所在地址', value: [] },
  { label: '反馈信息描述', value: '' },
  { label: '预估等级', value: [] },
  { label: '反馈日期时间', value: [] }
]);
//获取省份列表
const getProvinceList = async () => { 
  const result = await getProv();
  provinceList.value = result.data;
}


// 获取城市列表
const getCityList = async (province) => {
  if (!province) {
    cityList.value = [];
    return;
  }
  try {
    const result = await getCityByProv(province);
    if (result.code === 200) {
      cityList.value = result.data;
    } else {
      ElMessage.error('获取城市列表失败');
      cityList.value = [];
    }
  } catch (error) {
    console.error('获取城市列表失败', error);
    ElMessage.error('网络异常，请稍后再试');
    cityList.value = [];
  }
}

// 更新网格员列表
const updateGridWorkers = async (province, city) => {
  if (province && city ) {
    try {
      const result = await getGridWorkerByCity(province, city);
      if (result.code === 200) {
        gridWorkerList.value = result.data;
      } else {
        ElMessage.error('获取网格员列表失败');
        gridWorkerList.value = [];
      }
    } catch (error) {
      console.error('获取网格员列表失败', error);
      ElMessage.error('网络异常，请稍后再试');
      gridWorkerList.value = [];
    }
  } else {
    gridWorkerList.value = [];
  }
};

// 监听是否异地指派的状态变化
watch(
  () => assignmentForm.value.isRemoteAssignment,
  async (isRemote) => {
    if (isRemote) {
      // 异地指派：加载所有省份
      await getProvinceList();
      console.log('我是省份列表',provinceList.value);
      assignmentForm.value.province = '';
      assignmentForm.value.city = '';
      assignmentForm.value.remoteAssignee = '';
      cityList.value = [];
      gridWorkerList.value = [];
      console.log('我是省份列表',provinceList.value);
    } else {
      // 非异地指派：使用反馈者的省份和城市
      assignmentForm.value.province = feedbackProvince.value;
      assignmentForm.value.city = feedbackCity.value;
      assignmentForm.value.remoteAssignee = '';
      provinceList.value = [{ name: feedbackProvince.value }];
      cityList.value = [{ name: feedbackCity.value }];
      // 初始化网格员列表
      await updateGridWorkers(feedbackProvince.value, feedbackCity.value);
    }
  }
);
// 监听省份选择变化
watch(
  () => assignmentForm.value.province,
  async (newProvince) => {
    if (assignmentForm.value.isRemoteAssignment) {
      await getCityList(newProvince);
      console.log('获取城市列表',cityList.value);
      
      if (newProvince) {
        await updateGridWorkers(newProvince, assignmentForm.value.city);
      }
    }
  }
);
// 监听城市选择变化
watch(
  () => assignmentForm.value.city,
  async (newCity) => {
    if (assignmentForm.value.isRemoteAssignment && assignmentForm.value.province) {
      await updateGridWorkers(assignmentForm.value.province, newCity);
    }
  }
);

// const updateGridWorkers = async (province, city) => {
//   if (province && city) {
//     const result = await getGridWorkerByCity(province, city);
//     if (result.code === 200) {
//       gridWorkerList.value = result.data;
//     } else {
//       ElMessage.error('获取网格员列表失败');
//       gridWorkerList.value = [];
//     }
//   } else {
//     gridWorkerList.value = [];
//   }
// };


// 根据 id 获取详细数据并填充到表格中
onMounted(async () => {
  const id = localStorage.getItem('GridWorkerAssignmentId');
  const result = await getGridWorker(id);
  detailData.value = [
    { label: '公众监督反馈信息编号', value: result.data.id },
    { label: '反馈者信息', value: [result.data.supervisorName, result.data.gender] },
    { label: '反馈者联系电话', value: result.data.phone },
    { label: '反馈信息所在地址', value: [result.data.gridProvince, result.data.gridCity, result.data.address] },
    { label: '反馈信息描述', value: result.data.description },
    { label: '预估等级', value: result.data.estimatedAqiLevel },
    { label: '反馈日期时间', value: result.data.feedbackTime }
  ];

  // 设置反馈者的省份和城市
  feedbackProvince.value = result.data.gridProvince;
  feedbackCity.value = result.data.gridCity;

  //存储反馈信息ID
  feedbackId.value = result.data.id;
  // 初始化指派表单
  assignmentForm.value.province = feedbackProvince.value;
  assignmentForm.value.city = feedbackCity.value;
  provinceList.value = [{ name: feedbackProvince.value }];
  cityList.value = [{ name: feedbackCity.value }];

  /// 非异地指派时加载网格员
    if (!assignmentForm.value.isRemoteAssignment) {
      await updateGridWorkers(feedbackProvince.value, feedbackCity.value);
    }
});

// 返回上一页的函数
const goBack = () => {
  router.go(-1);
};
//指派反馈任务
const handleAssignment = async () => {
  // 验证是否选择了网格员
  if (!assignmentForm.value.remoteAssignee) {
    ElMessage.warning('请选择要指派的网格员');
    return;
  }
  
  // 验证反馈ID是否存在
  if (!feedbackId.value) {
    ElMessage.warning('未获取到反馈信息编号');
    return;
  }
  
  try {
    // 传递两个参数：feedbackId和remoteAssignee
    const result = await assignTask(feedbackId.value, assignmentForm.value.remoteAssignee);
    
    if (result.code === 200) {
      ElMessage.success('指派成功');
      router.go(-1); // 返回上一页
    } else {
      ElMessage.error(result.message || '指派失败');
    }
  } catch (error) {
    console.error('指派失败', error);
    ElMessage.error('网络异常，请稍后再试');
  }
};

</script>

<template>
  <div class="grid-worker-assignment">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>公众监督数据管理</el-breadcrumb-item>
      <el-breadcrumb-item>指派网格员</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 返回按钮 -->
    <el-button type="primary" @click="goBack" style="float: right; margin-top: -30px;">返回</el-button>

    <!-- 表格展示详细信息 -->
    <el-table :data="detailData" border style="width: 100%; margin-top: 20px;">
      <el-table-column prop="label" label="" width="250" align="center"></el-table-column>
      <el-table-column prop="value" label="" align="left">
        <template #default="scope">
          <div v-if="Array.isArray(scope.row.value)">
            <el-tag v-for="tag in scope.row.value" :key="tag" style="margin-right: 5px;">{{ tag }}</el-tag>
          </div>
          <div v-else>{{ scope.row.value }}</div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 指派操作区域 -->
    <div style="margin-top: 20px;">
      <el-form :model="assignmentForm" label-width="120px">
        <el-form-item label="是否异地指派">
          <el-switch v-model="assignmentForm.isRemoteAssignment"></el-switch>
        </el-form-item>
        <el-form-item label="省区域">
          <el-select v-model="assignmentForm.province" placeholder="请选择省" :disabled="!assignmentForm.isRemoteAssignment">
            <el-option v-for="p in provinceList"  :label="p" :value="p"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="市区域">
          <el-select v-model="assignmentForm.city" placeholder="请选择市" :disabled="!assignmentForm.isRemoteAssignment">
            <el-option v-for="c in cityList"  :label="c" :value="c"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="异地指派给">
          <el-select v-model="assignmentForm.remoteAssignee" placeholder="请选择指派人">
            <el-option
              v-for="worker in gridWorkerList"
              :key="worker.id"
              :label="worker.name"
              :value="worker.workerCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAssignment">指派</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>



<style scoped>
.grid-worker-assignment {
  padding: 20px;
}

.el-breadcrumb {
  margin-bottom: 20px;
}
</style>